package aor2.components;

public class FlipFlopRS extends FlipFlop {

	public FlipFlopRS(boolean state, Signal r, Signal s, Signal out) {
		super(state);
		this.r = r;
		this.s = s;
		this.q = out;
	}

	public FlipFlopRS(Signal r, Signal s, Signal out) {
		super(false);
		this.r = r;
		this.r.addDestinationElementIO(this);
		this.s = s;
		this.s.addDestinationElementIO(this);
		this.q = out;
		this.q.addSourceElementIO(this);
	}

	private Signal r, s, q;

	@Override
	public void in() throws FlipFlopException {
		if (r == null) {
			throw new FlipFlopException("signal R is not connected.");
		}
		if (s == null) {
			throw new FlipFlopException("signal S is not connected.");
		}

		if (r.isActive() && s.isActive()) {
			throw new FlipFlopRSException(
					"Active signals R, S. State unpredictable.");
		}
		if (r.isActive()) {
			state = false;
		} else if (s.isActive()) {
			state = true;
		}
	}

	@Override
	public void out() throws FlipFlopException {
		if (q == null) {
			throw new FlipFlopException("signal Q is not connected.");
		}
		q.setActive(state);
	}

	public Signal getOut() {
		return q;
	}

}
